﻿//  --------------------------------
//  Copyright (c) AW Systems, Inc. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://www.codeplex.com/SLAM/license
//  ---------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Slam.SharePoint
{
	public static class SPListExtender
	{
		public static void AddSlamPropertiesField(this SPList list)
		{
			if (!list.Fields.ContainsField("SLAM Properties"))
			{
				list.ParentWeb.AllowUnsafeUpdates = true;
				SPField newField = list.Fields.CreateNewField("Text", "SLAM Properties");
				newField.Hidden = true;
				list.Fields.Add(newField);
				list.Update();
			}
		}

		/// <summary>
		/// Gets a List Item from the given list with the given SLAM ID.
		/// </summary>
		/// <param name="list">The List from which to get the List Item</param>
		/// <param name="slamId">SLAM ID of a List Item</param>
		/// <returns></returns>
		public static SPListItem GetItemBySlamId(this SPList list, string slamId)
		{
			SPQuery query = new SPQuery();
			query.ViewAttributes = "Scope='RecursiveAll'";
			query.Query = @"	<Where>
									<Eq>
										<FieldRef Name='SLAM_x0020_ID' />
										<Value Type='Text'>" + slamId + @"</Value>
									</Eq>
								</Where>";

			SPListItemCollection listItems = list.GetItems(query);
			SPListItem listItem = null;
			foreach (SPListItem queriedListItem in listItems)
			{
				listItem = queriedListItem;
				break;
			}

			if (listItem == null)
			{
				try
				{
					list.GetItemByUniqueId(new Guid(slamId));
				}
				catch { }
			}

			return listItem;
		}
	}
}
